package com.zhangzhan.base.common_model.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhangzhan.base.common_model.entity.User;
import com.zhangzhan.base.common_model.pojo.LoginUser;
import com.zhangzhan.base.common_model.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 重写UserDetailsService接口
 * @date 2024/2/2 22:35
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     *       prams username 是AuthenticationManager传过来的
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询数据库
        User user = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, username));

        //判断是否存在
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误!");
        }

        //存在返回
        return new LoginUser(user);
    }
}
